import sys, os
try:
        import pygtk
        pygtk.require("2.0")
except:
        pass
try:
        import gtk
        import gtk.glade
	import pango
except:
        sys.exit(1)
from simpledcpp.core.base import DCPPPart, DCPPEvent
from simpledcpp.gui.base import gtk_lock_required
class ChatWindow(DCPPPart):
        def __init__(self, parent):
                DCPPPart.__init__(self, parent)
                self.Events.Subscribe("ON_PRIVATE_MESSAGE",self._message)
		self.Events.Subscribe("ON_HUB_DISCONNECTED", self._disconnected)
		self.Events.Subscribe("USER_OFFLINE", self._useroff)
		self.Events.Subscribe("USER_ONLINE", self._useron)
                self._buf = gtk.TextBuffer()
                self._txtwidget = gtk.TextView(self._buf)
                self._txtwidget.set_border_width(2)
                self._txtwidget.set_editable(False)
                self._txtwidget.set_wrap_mode(gtk.WRAP_WORD)
		self._txtwidget.set_cursor_visible(False)
                self._txtwidget.show()
                self._widget = gtk.ScrolledWindow()
                self._widget.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
                self._widget.add(self._txtwidget)
                self._widget.show()
                self._widget.set_size_request(400, 200)
	@gtk_lock_required
	def _disconnected(self, Event):
		hub, why = Event.userdata
		self.add(_("You disconnect from hub with this user. User now offline.\n"))
	@gtk_lock_required
	def _useroff(self, Event):
#		print "Useroff"
		hub , nick = Event.userdata
		if hub == self.parent._hub and self.parent._nickname == nick:
			self.add(_("User offline.\n"))

	@gtk_lock_required
	def _useron(self, Event):
		hub, nick = Event.userdata
		if hub == self.parent._hub and self.parent._nickname == nick:
			self.add(_("User online.\n"))

	@gtk_lock_required
        def _message(self, Event):
		hub, to, fm, mg = Event.userdata
                if fm == self.parent._nickname:
			#mg = mg.replace("<","&lt;").replace(">","&gt;")
                        self.parse_insert("%s"%(mg))

	def parse_insert(self, mg):
		try:
                	index = mg.index("://")
                        for i in mg.split(' '):
                        	try:
                                	i.index("://")
                                        tag = self._buf.create_tag()
                                        tag.set_property("foreground", "blue")
                                        tag.set_property("foreground-set", True)
					tag.set_property("underline", pango.UNDERLINE_SINGLE)
					tag.set_property("underline-set", True)
                                        self.add("%s"%i, tag)
					self.add(" ")
                                except:
                                        self.add("%s "%i)
                        self.add("\n")
                        return
		except:
                        pass


                try:
                        index = mg.index("magnet:")
                        for i in mg.split(' '):
                                try:
                                        i.index("magnet:")
                                        tag = self._buf.create_tag()
                                        tag.set_property("foreground", "blue")
                                        tag.set_property("foreground-set", True)
                                        tag.set_property("underline", pango.UNDERLINE_SINGLE)
                                        tag.set_property("underline-set", True)
                                        self.add("%s"%i, tag)
					self.add(" ")
                                except:
                                        self.add("%s "%i)
                        self.add("\n")
                        return
                except:
                        pass
                self.add("%s\n"%(mg))

	def _tagevent(self,texttag = None, widget = None, event = None, iter = None, param = None):
		if event.type == gtk.gdk.BUTTON_PRESS and event.button == 1:
			if param.split(':')[0] == 'magnet':
				self.Event(DCPPEvent("OPEN_MAGNET", (param,)))

        def add(self, message, Tag = None):
                iter = self._buf.get_iter_at_offset(self._buf.get_char_count())
		if Tag == None:
	                self._buf.insert(iter, message)
		else:
			Tag.connect("event", self._tagevent, message)
			self._buf.insert_with_tags(iter, message, Tag)
                iter = self._buf.get_iter_at_offset(self._buf.get_char_count())
                self._txtwidget.scroll_to_iter(iter,0, True)

	def Close(self, *args, **kwargs):
                self.Events.Unsubscribe("ON_PRIVATE_MESSAGE",self._message)
                self.Events.Unsubscribe("USER_OFFLINE", self._useroff)
                self.Events.Unsubscribe("USER_ONLINE", self._useron)
		self.Events.Unsubscribe("ON_HUB_DISCONNECTED", self._disconnected)

class PrivatePage(DCPPPart):
	def activate(self, *args, **kwargs):
		self.Event(DCPPEvent("LSB",("",)))

	def __init__(self, parent, nickname, hub = None):
		DCPPPart.__init__(self, parent)
		if hub == None:
			self.name = nickname
		else:
			self.name = nickname + ':' + hub
		self._hub = hub
		self._nickname = nickname
		self.type = 'private'
		self._widget = gtk.VBox()
		self._chatwindow = ChatWindow(self)
		self._widget.pack_start(self._chatwindow._widget)
		self.Entry = gtk.Entry()
		self.Entry.connect("key-press-event", self._onkey)
		self.Entry.show()
		self._widget.pack_start(self.Entry, False, False)
		self._widget.show()
		
	def _onkey(self, widget, Event, *args, **kwargs):
                if Event.keyval == 65293 and self.Entry.get_text() != "":
		        text = self.Entry.get_text()
                        self.Event(DCPPEvent("MESSAGE_TO", (self._hub,self._nickname, text)))
                        self.Entry.set_text("")
			self._chatwindow.parse_insert("<%s> %s"%(self.settings.get("nickname"), text))

	def Close(self, *args, **kwargs):
		self._chatwindow.Close()
		pass

